#!/bin/sh

#
# Local build server script (generously speaking) to call from cron at
# suitable intervals. All paths need to be changed, obviously.
#

# Directory to checkout to
SVNLOCAL=/home/henrik/acreo/svn/

# Only torrent_control has proper CMake build files atm
SVNREMOTE=http://wiki.testbed.se:65432/repos/p2pmediaplayer/sandbox/torrent_control

# Directory to build in
BUILDDIR=/home/henrik/acreo/build

# Lock created from notify.py
SVNLOCK=/home/henrik/projects/proj/acreo/build.me

# "Done" created from this script
BUILDDONE=/home/henrik/projects/proj/acreo/build.done

# Locking between builds
BUILDLOCK=/home/henrik/projects/proj/acreo/build.lock

# Build and subversion log files
BUILDLOG=/home/henrik/projects/proj/acreo/build-`date +%Y%m%d-%H.%M.%S`.log
SVNLOG=/home/henrik/projects/proj/acreo/svn-`date +%Y%m%d-%H.%M.%S`.log

# We don't want multiple builds running at the same time
if [ -f $BUILDLOCK ]; then
	 echo "Build aldready in progress, exiting"
	 exit 1
fi

# Create lock
touch $BUILDLOCK

# Building for the first time?
if [ ! -f $BUILDDONE ]; then
	 echo "Building for the first time"
	 touch -d19900101 $BUILDDONE
	 touch $SVNLOCK
fi

# Clean up from last build
rm -rf $SVNLOCAL
rm -rf $BUILDDIR
mkdir $SVNLOCAL
mkdir $BUILDDIR

# Only bother to build if the subversion callback has been touched lately
# ^-- Not as bad as it sounds, honestly.
if [ $SVNLOCK -nt $BUILDDONE ]; then
	 echo "New revision available, starting build"
	 svn co $SVNREMOTE $SVNLOCAL > $SVNLOG 2>&1

	 # Extract revision
	 REVISION=`svn info $SVNLOCAL | tail -n7 | head -n1`
	 echo "Building $REVISION" > $BUILDLOG

	 cd $BUILDDIR
	 cmake $SVNLOCAL >> $BUILDLOG 2>&1
	 make test >> $BUILDLOG 2>&1
else
	 echo "Nothing new to build, exiting"
fi

# Update build notification and unlock
touch $BUILDDONE
rm $BUILDLOCK
